package com.wuzf.navigation_test.ui;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.paging.DataSource;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;

public abstract class AbsViewModel<T> extends ViewModel {

    private LiveData<PagedList<T>> liveData;
    protected MutableLiveData<Boolean> boundaryLiveData = new MutableLiveData<>();

    public AbsViewModel() {
        init();
    }

    public MutableLiveData<Boolean> getBoundaryLiveData() {
        return boundaryLiveData;
    }

    public LiveData<PagedList<T>> getLiveData() {
        return liveData;
    }

    private void init() {
        PagedList.Config config = new PagedList.Config.Builder()
                .setPageSize(10)
                .setInitialLoadSizeHint(12)
                .setMaxSize(100)
                .build();
        liveData = new LivePagedListBuilder(factory, config)
                // 设置初始加载传递给pageList的值
                .setInitialLoadKey(0)
                .setBoundaryCallback(boundaryCallback)
                .build();
    }

    DataSource.Factory factory = new DataSource.Factory() {
        @NonNull
        @Override
        public DataSource create() {
            return createDataSource();
        }
    };

    PagedList.BoundaryCallback<T> boundaryCallback = new PagedList.BoundaryCallback<T>() {

        /**
         * 获取到空值的时候
         */
        @Override
        public void onZeroItemsLoaded() {
            super.onZeroItemsLoaded();
            boundaryLiveData.postValue(true);
        }

        /**
         * 第一条数据被加载的时候
         * @param itemAtFront
         */
        @Override
        public void onItemAtFrontLoaded(@NonNull T itemAtFront) {
            super.onItemAtFrontLoaded(itemAtFront);
            boundaryLiveData.postValue(false);
        }

        /**
         * 最后一条数据被加载的时候
         * @param itemAtEnd
         */
        @Override
        public void onItemAtEndLoaded(@NonNull T itemAtEnd) {
            super.onItemAtEndLoaded(itemAtEnd);
        }
    };

    public abstract DataSource createDataSource();
}
